﻿//**************************
//开发人员：Morning Sun QQ:576830428  微信:MorningSun0125
//业务范围：网站开发、小程序开发、web应用开发,桌面程序开发,工控类软件开发等
//开发日期：2016年1月10日
//版本号：Version 3.0 CopyRight 2011-2029
//**************************
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.ComponentModel;


//该类实现access数据库操作
namespace FileServer
{

    public abstract class DbHelperOledb
    {

        #region  成员变量
        //数据库连接字符串		
        private static string connectionString = PubConstant.ConnectionString;

        /// <summary>
        /// 设置数据库连接
        /// </summary>
        /// <param name="DbName"></param>
        public static void SetDataBase(string  DbName)
        {
            if (DbName != null && DbName != "")
            {
                connectionString = PubConstant.GetConfigByKey(DbName);
            }
            else
            {
                connectionString = PubConstant.ConnectionString;
            }
        }

        #endregion 


        #region 默认构造函数
       /// <summary>
        /// 构造函数
       /// </summary>
        public DbHelperOledb()
        {
        }
        #endregion


        #region  执行简单SQL语句

        #region 检测记录是否存在：Exists(string strSql)
        /// <summary>
        /// 查询记录是否存在
        /// </summary>
        /// <param name="strSql">SQL语句</param>
        /// <returns></returns>
        public static bool Exists(string strSql)
        {
            object obj = DbHelperOledb.GetSingle(strSql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion


        #region 执行不需返回结果的sql语句：ExecuteSql(string SQLString)
        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                using (OleDbCommand cmd = new OleDbCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.OleDb.OleDbException E)
                    {
                        connection.Close();
                        throw new Exception(E.Message);
                    }
                }
            }
        }
        #endregion


        #region 执行无返回结果的sql语句（需要传入库连接字符串）：ExecuteSqlAlertTable(string SQLString, string connectionString)
        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="connectionString">连接字符串</param>
        /// date 2008-11-21 for 更新程序路径设置
        /// <returns>影响的记录数</returns>
        public static int ExecuteSqlAlertTable(string SQLString, string connectionString)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                using (OleDbCommand cmd = new OleDbCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        //cmd.ExecuteScalar();
                        return rows;
                    }
                    catch (System.Data.OleDb.OleDbException E)
                    {
                        connection.Close();
                        throw new Exception(E.Message);
                    }
                }
            }
        }
        #endregion


        #region 执行sql语句返回首行首列：ExecuteScalar(string SQLString)
        /// <summary>
        /// 返回首行首列
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>首行首列值</returns>
        public static string ExecuteScalar(string SQLString)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                using (OleDbCommand cmd = new OleDbCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        string rows = cmd.ExecuteScalar().ToString();
                        return rows;
                    }
                    catch (System.Data.OleDb.OleDbException E)
                    {
                        connection.Close();
                        throw new Exception(E.Message);
                    }
                }
            }
        }
        #endregion


        #region 查找某个表某字段的最大值：GetMaxStringID(string FieldName, string TableName)
        /// <summary>
        /// 获取表某个字段的最大值
        /// </summary>
        /// <param name="FieldName">字段名</param>
        /// <param name="TableName">表名</param>
        /// <returns>string</returns>
        public static string GetMaxStringID(string FieldName, string TableName)
        {
            string strsql = "select max(" + FieldName + ") from " + TableName;
            object obj = GetSingle(strsql);
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                return "1";
            }
            else
            {
                return obj.ToString();
            }

        }
        #endregion


        #region 执行多条sql语句（以数组形式传入）：ExecuteSqlTran(ArrayList SQLStringList)
        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>  
        public static void ExecuteSqlTran(ArrayList SQLStringList)
        {
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                conn.Open();
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = conn;
                OleDbTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        string strsql = SQLStringList[n].ToString();
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                }
                catch (System.Data.OleDb.OleDbException E)
                {
                    tx.Rollback();
                    throw new Exception(E.Message);
                }
            }
        }
        #endregion


        #region 执行复杂字段的数据写入（某个）：ExecuteSql(string SQLString, string content)
        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章，有特殊符号，可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, string content)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                OleDbCommand cmd = new OleDbCommand(SQLString, connection);
                System.Data.OleDb.OleDbParameter myParameter = new System.Data.OleDb.OleDbParameter("@content", OleDbType.Variant);
                myParameter.Value = content;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.OleDb.OleDbException E)
                {
                    throw new Exception(E.Message);
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }

        public static int ExecuteScalar(string SQLString, string content)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                OleDbCommand cmd = new OleDbCommand(SQLString, connection);
                System.Data.OleDb.OleDbParameter myParameter = new System.Data.OleDb.OleDbParameter("@content", OleDbType.Variant);
                myParameter.Value = content;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = int.Parse(cmd.ExecuteScalar().ToString());
                    return rows;
                }
                catch (System.Data.OleDb.OleDbException E)
                {
                    throw new Exception(E.Message);
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }
        #endregion


        #region 操作带有image字段的表： ExecuteSqlInsertImg(string strSQL, byte[] fs)
        /// <summary>
        /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
        /// </summary>
        /// <param name="strSQL">SQL语句</param>
        /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                OleDbCommand cmd = new OleDbCommand(strSQL, connection);
                System.Data.OleDb.OleDbParameter myParameter = new System.Data.OleDb.OleDbParameter("@fs", OleDbType.Binary);
                myParameter.Value = fs;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.OleDb.OleDbException E)
                {
                    throw new Exception(E.Message);
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }
        #endregion


        #region 执行无需返回结果的sql语句（返回object）：GetSingle(string SQLString)
        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public static object GetSingle(string SQLString)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                using (OleDbCommand cmd = new OleDbCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.OleDb.OleDbException e)
                    {
                        connection.Close();
                        throw new Exception(e.Message);
                    }
                }
            }
        }
        #endregion


        #region 执行返回oledbdatareader对象的sql：ExecuteReader(string strSQL)
        /// <summary>
        /// 执行查询语句，返回OleDbDataReader
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>OleDbDataReader</returns>
        public static OleDbDataReader ExecuteReader(string strSQL)
        {
            OleDbConnection connection = new OleDbConnection(connectionString);
            OleDbCommand cmd = new OleDbCommand(strSQL, connection);
            try
            {
                connection.Open();
                OleDbDataReader myReader = cmd.ExecuteReader();
                return myReader;
            }
            catch (System.Data.OleDb.OleDbException e)
            {
                throw new Exception(e.Message);
            }

        }
        #endregion


        #region  执行返回dataset对象的sql：Query(string SQLString)
        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    OleDbDataAdapter command = new OleDbDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.OleDb.OleDbException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }
        #endregion


        #region 执行返回dataset对象的sql：GetDataSet(string SQLString)
        /// <summary>
        /// 执行查询语句，返回DataSet，作用和Query相同，名字更直观些
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet GetDataSet(string SQLString)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    OleDbDataAdapter command = new OleDbDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.OleDb.OleDbException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }
        #endregion


        #region 执行返回datatable对象的sql：GetDataTable(string sql)
        /// <summary>
        /// 返回一个DataTable
        /// </summary>
        /// <param name="sql">查询语句</param>
        /// <returns></returns>
        public static DataTable GetDataTable(string sql)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    OleDbDataAdapter Da = new OleDbDataAdapter(sql, connection);
                    DataTable Dt = new DataTable();
                    Da.Fill(Dt);
                    return Dt;
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message, e);
                }
            }
        }

        #endregion


        #region 执行新增的sql语句并返回执行语句的主键id：GetMainKey(string SQLString, string KeyName, string TableName)
        /// <summary>
        /// 执行新增的sql语句并返回执行语句的主键id
        /// </summary>
        /// <param name="SQLString">sql添加执行语句</param>
        /// <param name="KeyName">表名</param>
        /// <param name="TableName">主键名称</param>
        /// <returns></returns>
        public static int GetMainKey(string SQLString, string KeyName, string TableName)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                using (OleDbCommand cmd = new OleDbCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        cmd.ExecuteNonQuery();
                        int KeyID = int.Parse(GetMaxStringID(KeyName, TableName));
                        //cmd.ExecuteScalar();
                        return KeyID;
                    }
                    catch (System.Data.OleDb.OleDbException E)
                    {
                        connection.Close();
                        throw new Exception(E.Message);
                    }
                }
            }
        }
        #endregion


        #region 执行翻页查询： PagedataSet(string sqlstr, int pageindex, int pagesize, string table)
        /// <summary>
        /// 返回翻页的dataset
        /// </summary>
        /// <param name="sqlstr">查询sql语句</param>
        /// <param name="pageindex">当前页</param>
        /// <param name="pagesize">每页大小</param>
        /// <param name="table">表名</param>
        /// <returns></returns>
        public static DataSet PagedataSet(string sqlstr, int pageindex, int pagesize, string table)
        {
            DataSet ds = new DataSet();
            OleDbDataAdapter da = new OleDbDataAdapter();
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                connection.Open();
                try
                {
                    OleDbCommand command = new OleDbCommand(sqlstr, connection);
                    da.SelectCommand = command;
                    da.Fill(ds, pageindex*pagesize, pagesize, table);
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
                finally
                {
                    connection.Close();
                }
            }
            return ds;
        }
        #endregion


        #region 执行查询语句，返回DataSet：PageQuery(string SQLString, int PageIndex, int PageSize, params SqlParameter[] cmdParms)
        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet PageQuery(string SQLString, int PageIndex, int PageSize, params OleDbParameter[] cmdParms)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                OleDbCommand cmd = new OleDbCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, PageIndex*PageSize, PageSize, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (System.Data.SqlClient.SqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
        }
        #endregion

        #endregion


        #region 执行带参数的SQL语句


        #region 执行返回影响记录数的sql： ExecuteSql(string SQLString, params OleDbParameter[] cmdParms)
        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, params OleDbParameter[] cmdParms)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                using (OleDbCommand cmd = new OleDbCommand())
                {
                    try
                    {
                        if (cmdParms != null)
                        {
                            foreach (OleDbParameter p in cmdParms)
                            {
                                if (p.Value == null)
                                {
                                    p.Value = DBNull.Value;
                                }
                                else if (p.Value.ToString() == "0001-1-1 0:00:00")
                                {
                                    p.Value = DateTime.Now.AddYears(-100);
                                }

                            }

                        }
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (System.Data.OleDb.OleDbException E)
                    {
                        throw new Exception(E.Message);
                    }
                    catch (Exception ee)
                    {
                        throw new Exception(ee.Message);
                    }
                }
            }
        }
        #endregion


        #region 执行返回首行首列的sql：ExecuteScalar(string SQLString, params OleDbParameter[] cmdParms)
        /// <summary>
        /// 返回首行首列
        /// </summary>
        /// <param name="SQLString"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public static int ExecuteScalar(string SQLString, params OleDbParameter[] cmdParms)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                using (OleDbCommand cmd = new OleDbCommand())
                {
                    try
                    {
                        if (cmdParms != null)
                        {
                            foreach (OleDbParameter p in cmdParms)
                            {

                                if (p.Value == null)
                                {
                                    p.Value = DBNull.Value;
                                }
                                else if (p.Value.ToString() == "0001-1-1 0:00:00")
                                {
                                    p.Value = DateTime.Now.AddYears(-100);
                                }

                            }
                        }
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = int.Parse(cmd.ExecuteScalar().ToString());
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (System.Data.OleDb.OleDbException E)
                    {
                        throw new Exception(E.Message);
                    }
                    catch (Exception ee)
                    {
                        throw new Exception(ee.Message);
                    }
                }
            }
        }
        #endregion


        #region 执行多条sql语句 :ExecuteSqlTran(Hashtable SQLStringList)
        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表（key为sql语句，value是该语句的OleDbParameter[]）</param>
        public static bool  ExecuteSqlTran(Hashtable SQLStringList)
        {
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                conn.Open();
                using (OleDbTransaction trans = conn.BeginTransaction())
                {
                    OleDbCommand cmd = new OleDbCommand();
                    try
                    {
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            string cmdText = myDE.Key.ToString();
                            OleDbParameter[] cmdParms = (OleDbParameter[])myDE.Value;
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                        return true;
                    }
                    catch (System.Data.OleDb.OleDbException E)
                    {
                        trans.Rollback();
                        return false;
                        throw new Exception(E.Message);
                    }
                }
            }
        }
        #endregion


        #region 执行返回object对象的sql：GetSingle(string SQLString, params OleDbParameter[] cmdParms)
        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public static object GetSingle(string SQLString, params OleDbParameter[] cmdParms)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                using (OleDbCommand cmd = new OleDbCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.OleDb.OleDbException e)
                    {
                        throw new Exception(e.Message);
                    }
                }
            }
        }
        #endregion


        #region 执行返回oledbdatareader对象的sql：ExecuteReader(string SQLString, params OleDbParameter[] cmdParms)
        /// <summary>
        /// 执行查询语句，返回OleDbDataReader
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>OleDbDataReader</returns>
        public static OleDbDataReader ExecuteReader(string SQLString, params OleDbParameter[] cmdParms)
        {
            OleDbConnection connection = new OleDbConnection(connectionString);
            OleDbCommand cmd = new OleDbCommand();
            try
            {
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                OleDbDataReader myReader = cmd.ExecuteReader();
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (System.Data.OleDb.OleDbException e)
            {
                throw new Exception(e.Message);
            }

        }
        #endregion


        #region 执行返回dataset对象的sql： Query(string SQLString, params OleDbParameter[] cmdParms)
        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString, params OleDbParameter[] cmdParms)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                OleDbCommand cmd = new OleDbCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (System.Data.OleDb.OleDbException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
        }
        #endregion


        #endregion


        #region 存储过程操作


        #region 执行返回oledbreader对象的存储过程：RunProcedure(string storedProcName, IDataParameter[] parameters)
        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        public static OleDbDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
        {
            OleDbConnection connection = new OleDbConnection(connectionString);
            OleDbDataReader returnReader;
            connection.Open();
            OleDbCommand command = BuildQueryCommand(connection, storedProcName, parameters);
            command.CommandType = CommandType.StoredProcedure;
            returnReader = command.ExecuteReader();
            return returnReader;
        }
        #endregion


        #region 执行返回dataset对象的存储过程：RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName )
         ///<summary>
         ///执行存储过程
         ///</summary>
         ///<param name="storedProcName">存储过程名</param>
         ///<param name="parameters">存储过程参数</param>
         ///<param name="tableName">DataSet结果中的表名</param>
         ///<returns>DataSet</returns>
        public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName )
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                OleDbDataAdapter sqlDA = new OleDbDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters );
                sqlDA.Fill( dataSet, tableName );
                connection.Close();
                return dataSet;
            }
        }
        #endregion



        #region 执行返回影响记录数的存储过程：RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        /// <summary>
        /// 执行存储过程，返回影响的行数  
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="rowsAffected">影响的行数</param>
        /// <returns></returns>
        public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                int result;
                connection.Open();
                OleDbCommand command = BuildIntCommand(connection, storedProcName, parameters);
                rowsAffected = command.ExecuteNonQuery();
                result = (int)command.Parameters["ReturnValue"].Value;
                //Connection.Close();
                return result;
            }
        }

        #endregion


        #endregion


        #region 数据库操作辅助函数

        #region 初始化command对象的公共方法：PrepareCommand(OleDbCommand cmd, OleDbConnection conn, OleDbTransaction trans, string cmdText, OleDbParameter[] cmdParms)
        /// <summary>
        /// 实例化command对象的Parameter参数
        /// </summary>
        /// <param name="cmd">需要实例化的command对象</param>
        /// <param name="conn">command用到的connection对象</param>
        /// <param name="trans">command对象的事物对象</param>
        /// <param name="cmdText">command的sql语句</param>
        /// <param name="cmdParms">command的parameter参数</param>
        private static void PrepareCommand(OleDbCommand cmd, OleDbConnection conn, OleDbTransaction trans, string cmdText, OleDbParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {
                foreach (OleDbParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);

            }
        }
        #endregion


        #region 创建 OleDbCommand 对象实例：BuildQueryCommand(OleDbConnection connection, string storedProcName, IDataParameter[] parameters)
        /// <summary>
        /// 构建 OleDbCommand 对象(用来返回一个结果集，而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>OleDbCommand</returns>
        private static OleDbCommand BuildQueryCommand(OleDbConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            OleDbCommand command = new OleDbCommand(storedProcName, connection);
            command.CommandType = CommandType.StoredProcedure;
            foreach (OleDbParameter parameter in parameters)
            {
                command.Parameters.Add(parameter);
            }
            return command;
        }
        #endregion


        #region 创建 OleDbCommand 对象实例(用来返回一个整数值:BuildIntCommand(OleDbConnection connection, string storedProcName, IDataParameter[] parameters)
        /// <summary>
        /// 创建 OleDbCommand 对象实例(用来返回一个整数值) 
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>OleDbCommand 对象实例</returns>
        private static OleDbCommand BuildIntCommand(OleDbConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            OleDbCommand command = BuildQueryCommand(connection, storedProcName, parameters);
            command.Parameters.Add(new OleDbParameter("ReturnValue",
                OleDbType.Integer, 4, ParameterDirection.ReturnValue,
                false, 0, 0, string.Empty, DataRowVersion.Default, null));
            return command;
        }
        #endregion

        
        #region 判断sql是否合法(返回bool)：SafeSql(String sql_str)
        /// <summary>
        /// 传入用户输入判断是不是非法关键字
        /// </summary>
        /// <param name="sql_str">传入用户输入字符判断</param>
        /// <returns></returns>
        public static bool SafeSql(String sql_str)
        {//用#分割关键字
            string model_str = PubConstant.SafeSqlString.Trim();

            string[] model_split_str = model_str.Split('#');

            for (int i = 0; i < model_split_str.Length; i++)
            {
                if (sql_str.IndexOf(model_split_str[i]) >= 0)
                {
                    //>=0说明有关键字，否则说明没有关键字
                    return true;

                }
            }
            return false;
        }
        #endregion

        #endregion
    }

}

